
package com.scalar.chiptrack.alarms.jobs;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;

import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.AlarmUser;
import com.scalar.chiptrack.alarms.dao.AlarmDAO;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;



public class AlarmReminderJob extends JobHandler {


    public AlarmReminderJob() {
    }
    
    public void execute() throws Exception {

        LinkedList recpList = null;
        LinkedHashMap recpAlarmIdMap = new LinkedHashMap();
        
        try {
            recpList = AlarmDAO.loadToBeRespondedRecipients();
            if (recpList == null) {
                return;
            }
            
            AlarmUser alarmUser = null;
            String email = null;
            String userName = null;
            int alarmId = -1;
            
            int listSize = recpList.size();            
            LinkedHashSet alarmIdSet = null;
            HashSet allAlarmIdSet = new HashSet();
            
            System.out.println ("Number of users to be responded = " + listSize);
            
            for (int i=0; i<listSize; i++) {
                
                alarmUser = (AlarmUser) recpList.get(i);
                userName = alarmUser.getName();
                email = alarmUser.getEmail();
                alarmId = alarmUser.getAlarmId();
                
                allAlarmIdSet.add (alarmId+"");
                
                alarmIdSet = (LinkedHashSet) recpAlarmIdMap.get (userName + "|" + email);
                if (alarmIdSet == null) {
                    alarmIdSet = new LinkedHashSet();
                    recpAlarmIdMap.put (userName + "|" + email, alarmIdSet);
                }
                
                alarmIdSet.add (alarmId+"");
            }
                       
            HashMap alarmMap = AlarmDAO.loadAlarmByIdList (allAlarmIdSet.iterator());
            sendAlert (recpAlarmIdMap, alarmMap);
        }
        
        catch (Exception e) {
            System.err.println ("Exception while running AlarmReminderJob: " + e);
            e.printStackTrace();
            throw e;
        } 
    }
    
    
    private void sendAlert (LinkedHashMap recpAlarmIdMap, HashMap alarmMap) throws Exception {

        
        Iterator userEmailIterator = recpAlarmIdMap.keySet().iterator();
        String userAndEmail = null;
        Iterator alarmIdIterator = null;
        Alarm alarm = null;
        
        String subject = "ChipTrac: Notification response reminder";
        String from = ConfigManager.getSysAdminEmail();
        String to = null;
        StringBuffer message = new StringBuffer();
        
        String hostName = ConfigManager.getChipTracHost();
        String context = ConfigManager.getChipTracContext();
        
        while (userEmailIterator.hasNext()) {
            userAndEmail = (String) userEmailIterator.next();
            to = userAndEmail.substring (userAndEmail.indexOf('|')+1, userAndEmail.length());
            
            message.append ("<html><head><link href='http://").append (hostName).append ("/").append (context).append ("/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet><BR>\n");
            message.append ("</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'><BR>\n");
            message.append ("<IMG src='http://").append (hostName).append ("/").append (context).append ("/jsp/includes/images/scalar_logo.jpg' width=90 height=36 border=0>\n");
            message.append ("<center><h3>Notification Reminder</h3></center><p>Hi, Your response is still pending for these notifications. Please click on the links below to view the notification information in detail:<p>\n");
            message.append ("<table border='0' align='center' width='70%'>\n\t<tr bgcolor='#993333'><td><font color='#FFFFFF'>Alarm ID</font></td><td><font color='#FFFFFF'>Alarm Name</font></td><td><font color='#FFFFFF'>Alarm Type</font></td><td><font color='#FFFFFF'>Created On</font></td></tr>\n");
        
            alarmIdIterator = ((HashSet) recpAlarmIdMap.get (userAndEmail)).iterator();
            String[] bgColor = {"#DEE1E2", "#FFFFFF"};
            int i=0;
            
            while (alarmIdIterator.hasNext()) {
                alarm = (Alarm) alarmMap.get (alarmIdIterator.next());
                
                message.append ("<tr bgcolor='" + bgColor[(i++)%2] + "'><td><a href='http://").append (hostName).append ("/").append (context);
                message.append ("/alarmsWarnings.do?action=show&alarmId=").append (alarm.getId()).append ("&alarmType=").append (alarm.getType()).append ("' title='Click here to view details'>");                
                message.append (alarm.getId()).append ("</a></td><td>").append (alarm.getName()).append ("</td><td>");
                message.append (alarm.getType()).append ("</td><td>").append (StringUtils.formatDateToString (new Date (alarm.getCreatedOn()))).append ("</td></tr>\n");
            }
            
            message.append ("</table></body></html>\n");
            
            Mailer.send (from, to, subject, message.toString(), Mailer.CONTENT_TYPE_HTML);
            System.out.println ("NotificationReminder: Sent a reminder to " + to);
        }
    }

    
    public static void main (String[] args) throws Exception {
        new AlarmReminderJob().execute();
    }
}